	//
	//  UIView+GaDisplay.m
	//  productLine
	//
	//  Created by GikkiAres on 2019/2/26.
	//  Copyright © 2019 base. All rights reserved.
	//

#import "JsDisplayManager.h"
#import <objc/runtime.h>
#import "JsActivityReminderView.h"
#import "JsMaskView.h"
#import "JsBundleManager.h"

//TostView,需要手动关闭的view,用于网络请求
//MessageView,自动显示的view,用于消息提示
	//显示的次数
static int kToastCount;
  //self绑定的toastview.需要和一般的view分开.
static int kMessageReminderView;

@implementation UIView (GaDisplay)

static int kCompetionHanlder;
static int kDisplayStyle;
//container中实际显示的view,有可能不是self;
static int kDisplayView;
static int kMaskView;

//displayView关联containerView
static int kContainerView;
//显示的次数
//static int kDisplayCount;
static int kUndisplayTimer;

#pragma mark 1 Life Circle

#pragma mark 2 Basic Function
	//MaskBtn点击事件,如果触发了该事件,说明有MaskBtn,需要取消;
- (void)onMaskBtnClick {
	[self undisplay];
}


#pragma mark 3 Interface
- (void)displayInView:(UIView *)containerView {
	JsDisplayStyle * style = [JsDisplayStyle defaulStyle];
	[self displayInView:containerView withDisplayStyle:style undisplayCompletionHandler:nil];
}

/*此时的self,是该方法的调用者.
 需要保证此runloop中的frame是正确的.
 */
- (void)displayInView:(UIView *)containerView withDisplayStyle:(JsDisplayStyle *)style displayCompetinHandler:(void(^)(void))displayCompetinHandler undisplayCompletionHandler:(void(^)(void))undisplayCompletionHandler {
		//MARK:1 设置附加的样式
		//1.1 设置圆角样式 //增加shapelayer后,导致阴影看不见了....
	CAShapeLayer *shapeLayer = [CAShapeLayer layer];
		//	1.2 将shapelayer设置为圆角矩形.
	if(style.roundCorner>0) {
		shapeLayer.path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:style.muiRectCorner cornerRadii:CGSizeMake(style.roundCorner, style.roundCorner)].CGPath;
		self.layer.mask = shapeLayer;
	}
		//1.3 增加阴影效果
	UIView * displayView = self;
	if(style.mb_isHasShadow) {
		self.layer.borderColor = [UIColor blackColor].CGColor;
		self.layer.borderWidth = 0.5;
		
			//TODO: 增加阴影效果,由于设置了圆角,添加不进来,只能
			//增加一个shadowview.
		UIView * shadowView = [[UIView alloc] initWithFrame:self.frame];
		shadowView.frame = self.frame;
		shadowView.backgroundColor = [UIColor blackColor];
		shadowView.layer.shadowColor = [UIColor blackColor].CGColor;
		shadowView.layer.shadowRadius = 10.0f;
		if(style.muiRectCorner&&style.roundCorner) {
			shadowView.layer.cornerRadius = style.roundCorner;
		}
		shadowView.layer.shadowOpacity = 1.f;
		shadowView.layer.shadowOffset = CGSizeMake(0,0);
		
			//			//路径阴影
			//		UIBezierPath *path = [UIBezierPath bezierPath];
			//		CGFloat paintingWidth = 5;
			//		CGFloat paintingHeight = 5;
			//		[path moveToPoint:CGPointMake(-5, -5)];
			////		[path addLineToPoint:CGPointMake(10,10)];
			//
			//			//添加直线
			//		[path addLineToPoint:CGPointMake(paintingWidth /2, -15)];
			//		[path addLineToPoint:CGPointMake(paintingWidth +5, -5)];
			//		[path addLineToPoint:CGPointMake(paintingWidth +15, paintingHeight /2)];
			//		[path addLineToPoint:CGPointMake(paintingWidth +5, paintingHeight +5)];
			//		[path addLineToPoint:CGPointMake(paintingWidth /2, paintingHeight +15)];
			//		[path addLineToPoint:CGPointMake(-5, paintingHeight +5)];
			//		[path addLineToPoint:CGPointMake(-15, paintingHeight /2)];
			//		[path addLineToPoint:CGPointMake(-5, -5)];
			//
			//			//设置阴影路径
			//		self.layer.shadowPath = path.CGPath;
		[shadowView addSubview:self];
		displayView = shadowView;
		self.frame = self.bounds;
	}
	
	
		//全部采用maskView的方式.
		//如果有遮罩的话,是加在遮罩上的;
		//        UIView * vMask = [[UIView alloc]initWithFrame:superview.bounds];
	JsMaskView * btnMask = [[JsMaskView alloc]initWithFrame:containerView.bounds];
	
	
	[btnMask setBackgroundColor:style.maskColor];
	btnMask.alpha = style.mf_maskAlpha;
	if(style.mb_isMaskCancellable) {
		[btnMask addTarget:self action:@selector(onMaskBtnClick) forControlEvents:UIControlEventTouchUpInside];
	}
	
	
	
	[containerView addSubview:btnMask];
	[btnMask addSubview:displayView];
	//TODO: btnMask是可配置的.
//	[containerView addSubview:displayView];
	
	
	
	//关联相关对象
	//关联block和btnMask;
	objc_setAssociatedObject(self, @selector(onMaskBtnClick), btnMask, OBJC_ASSOCIATION_RETAIN);
	
	objc_setAssociatedObject(self, &kContainerView,containerView, OBJC_ASSOCIATION_RETAIN);
	//关联maskView
	objc_setAssociatedObject(self, &kMaskView,btnMask, OBJC_ASSOCIATION_RETAIN);
		//关联展示样式对象
	objc_setAssociatedObject(self, &kDisplayStyle,style, OBJC_ASSOCIATION_RETAIN);
		//关联取消的block
	if(undisplayCompletionHandler){
		objc_setAssociatedObject(self, &kCompetionHanlder, undisplayCompletionHandler, OBJC_ASSOCIATION_RETAIN);
	}
	
		//关联显示的时间
	if(style.mf_displayTime > 0) {
		__weak typeof(self) weakSelf = self;
		NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:style.mf_displayTime repeats:NO block:^(NSTimer * _Nonnull timer) {
			[weakSelf undisplay];
			[timer invalidate];
		}];
		objc_setAssociatedObject(self, &kUndisplayTimer, timer, OBJC_ASSOCIATION_RETAIN);
	}


	
	
		//MARK: StepB-1 计算displayView在superView的位置--targetFrame
	//
	CGRect targetFrame = [self targetFrameWithContainerSize:containerView.frame.size withStyle:style];
	
		//屏幕尺寸
	CGFloat f_screenWidth = [UIScreen mainScreen].bounds.size.width;
	CGFloat f_screenHeight = [UIScreen mainScreen].bounds.size.height;
	
	
	
	
		//MARK: Step:计算初始状态,位置,transform,alpha.
	CGRect startFrame = CGRectZero;
	CGAffineTransform startTransform = CGAffineTransformIdentity;
	CGFloat startAlpha = displayView.alpha;
	CGFloat targetAlpha = displayView.alpha;
	switch (style.displayAnimationType) {
		case JsDisplayAnimationTypeNone:{
			startFrame = targetFrame;
			break;
		}
		case JsDisplayAnimationTypeMoveFromRight:
				//从右边划过来 调整x为 screen.width;
			startFrame = targetFrame;
			startFrame.origin.x = f_screenWidth;
			
			break;
		case JsDisplayAnimationTypeMoveFromBottom:{
			startFrame = targetFrame;
			startFrame.origin.y = f_screenHeight;
			break;
		}
		case JsDisplayAnimationTypeMoveFromTop:{
			startFrame = targetFrame;
			startFrame.origin.y = -f_screenHeight;
			break;
		}
		case JsDisplayAnimationTypeShrink:{
			startFrame = targetFrame;
			startTransform = CGAffineTransformMakeScale(2, 2);
			startAlpha = 0;
			break;
		}
		default:{
			break;
		}
	}
	
		
	if(style.displayAnimationType != JsDisplayAnimationTypeNone) {
			//MARK: Step:执行动画
	displayView.frame = startFrame;
	displayView.alpha = startAlpha;
	displayView.transform = startTransform;
	
	
	[UIView animateWithDuration:style.mf_displayAnimationDuration delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
			//需要先调整transform,再设置frame,否则会有问题.
		displayView.transform = CGAffineTransformIdentity;
		displayView.frame = targetFrame;
		displayView.alpha = targetAlpha;
		
	} completion:^(BOOL finished) {
	}];
	}
	else {
			//需要先调整transform,再设置frame,否则会有问题.
		displayView.transform = CGAffineTransformIdentity;
		displayView.frame = targetFrame;
		displayView.alpha = targetAlpha;
	}
	
	
	//监听屏幕旋转的通知
	//监听屏幕方向的改变通知
	//TODO: when to remove?
//	[[NSNotificationCenter defaultCenter] addObserverForName:UIDeviceOrientationDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
//		CGSize containerSize = containerView.frame.size;
//		CGRect frame = [self targetFrameWithContainerSize:containerSize withStyle:style];
//		displayView.frame = frame;
//	}];
	
}

//根据当前父容器的大小和style,计算正确的frame
- (CGRect)calculateTargetFrame {
	UIView * containerView = objc_getAssociatedObject(self, &kContainerView);
	JsDisplayStyle * style = objc_getAssociatedObject(self, &kDisplayStyle);
	return [self targetFrameWithContainerSize:containerView.frame.size withStyle:style];
}

//根据containerSize计算TargetFrame
//size是自身的size.
- (CGRect)targetFrameWithContainerSize:(CGSize)containerSize withStyle:(JsDisplayStyle *)style {
	CGSize size = self.bounds.size;
	CGRect targetFrame = CGRectZero;
	CGFloat targetX = 0;
	CGFloat targetY = 0;
	CGFloat targetW = size.width;
	CGFloat targetH = size.height;
	
	switch (style.displayPosition) {
		case JsDisplayPositionCenter: {
			targetX = (containerSize.width-self.bounds.size.width)/2;
			targetY = (containerSize.height-self.bounds.size.height)/2;
			targetFrame = CGRectMake(0, targetY, targetW, targetH);
			break;
		}
		case JsDisplayPositionRight: {
				//displayView和containerView的右边对齐,垂直居中
			targetX = containerSize.width - size.width;
			targetY = (containerSize.height - size.height)/2;
			targetFrame = CGRectMake(targetX, targetY, size.width, size.height);
			
			break;
		}
		case JsDisplayPositionLeft: {
			break;
		}
		case JsDisplayPositionBottom: {
			targetX = (containerSize.width-self.bounds.size.width)/2;
			targetY = containerSize.height - size.height;
			targetFrame = CGRectMake(0, targetY, targetW, targetH);
			break;
		}
		case JsDisplayPositionTop: {
			targetX = (containerSize.width-self.bounds.size.width)/2;
			targetY = 0;
			targetFrame = CGRectMake(targetX, targetY, targetW, targetH);
			break;
		}
		case JsDisplayPositionCustom: {
			targetFrame = style.displayCustomFrame;
			targetX = targetFrame.origin.x;
			targetY = targetFrame.origin.y;
			break;
		}
		default:{
			break;
		}
	}
		//MARK: StepB-2 添加offset
	targetX += style.offset_displayPosition.horizontal;
	targetY += style.offset_displayPosition.vertical;
	targetFrame = CGRectMake(targetX, targetY, targetW, targetH);
	return targetFrame;
}


//undisplayCompletionHandler是undisplay之后的handler
- (void)displayInView:(UIView *)containerView withDisplayStyle:(JsDisplayStyle *)style undisplayCompletionHandler:(void(^)(void))handler {
	dispatch_async(dispatch_get_main_queue(), ^{
		[self displayInView:containerView withDisplayStyle:style displayCompetinHandler:nil undisplayCompletionHandler:handler];
	});
}

/**
 1,self是displayView.
 2,undisplay应该由displayView调用.
 3,containerView displayView:displayView
 4,displayView displayInView:containerView
 5,displayView undisplay
 6,containerView undisplayView:
 7,containerView undisplayAllView;
 */
- (void)undisplay{
		//屏幕尺寸
	CGFloat f_screenWidth = [UIScreen mainScreen].bounds.size.width;
	NSTimer * timer = objc_getAssociatedObject(self, &kUndisplayTimer);
	if(timer) {
		[timer invalidate];
		objc_setAssociatedObject(self, &kUndisplayTimer, nil, OBJC_ASSOCIATION_RETAIN);
	}
	UIView * displayView = self;
	JsDisplayStyle * style = objc_getAssociatedObject(self, &kDisplayStyle);
		//MARK: 1 计算结束的位置--finishFrame
	CGRect rc_currentFrame = self.frame;
	CGRect rc_finishFrame= rc_currentFrame;
	switch (style.undisplayAnimationType) {
		case JsUndisplayAnimationTypeNone:{
			[self remove];
			break;
		}
		case JsUndisplayAnimationTypeMoveToLeft:{
			//计算结束时的位置,-width
			rc_finishFrame.origin.x = -rc_currentFrame.size.width;
			[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
				displayView.frame = rc_finishFrame;
			} completion:^(BOOL finished) {
				[self remove];
			}];
			break;
		}
		case JsUndisplayAnimationTypeMoveToRight:{
			rc_finishFrame.origin.x = f_screenWidth;
			[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
				displayView.frame = rc_finishFrame;
			} completion:^(BOOL finished) {
				[self remove];
			}];
			break;
		}
		case JsUndisplayAnimationTypeMoveToBottom:{
			CGRect targetFrame = CGRectZero;
			CGFloat yTarget = displayView.superview.bounds.size.height;
			CGSize size = displayView.bounds.size;
			targetFrame = CGRectMake(0, yTarget, size.width, size.height);
			[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
				displayView.frame = targetFrame;
			} completion:^(BOOL finished) {
				[self remove];
			}];
			break;
		}
		case JsUndisplayAnimationTypeMoveToTop:{
			CGRect targetFrame = CGRectZero;
			CGFloat targetX = displayView.frame.origin.x;
			CGFloat yTarget = -displayView.bounds.size.height;
			CGSize size = displayView.bounds.size;
			targetFrame = CGRectMake(targetX, yTarget, size.width, size.height);
			[UIView animateWithDuration:0.3 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
				displayView.frame = targetFrame;
			} completion:^(BOOL finished) {
				[self remove];
			}];
			break;
		}
			
		default:{
			break;
		}
	}
	
	
}

- (void)undisplayWithAnimationType:(JsUndisplayAnimationType)animationType {
	JsDisplayStyle * style = objc_getAssociatedObject(self, &kDisplayStyle);
	style.undisplayAnimationType = animationType;
	[self undisplay];
}

/**
 displayView从父视图中移除,并释放关联资源.
 */
- (void)remove {
	[self removeFromSuperview];
	
	UIButton *btnMask = objc_getAssociatedObject(self, &kMaskView);
	if(btnMask) {
		[btnMask removeFromSuperview];
	}
	
		//置空所有关联
	//containerView
	objc_setAssociatedObject(self, &kContainerView, nil, OBJC_ASSOCIATION_RETAIN);
	//maskView
	objc_setAssociatedObject(self,  &kMaskView, nil, OBJC_ASSOCIATION_RETAIN);
	//displayStyle
	objc_setAssociatedObject(self, &kDisplayStyle, nil, OBJC_ASSOCIATION_RETAIN);
	
	
	void(^undisplayCompletionHandler)(void)  = objc_getAssociatedObject(self,&kCompetionHanlder);
	if(undisplayCompletionHandler) {
		undisplayCompletionHandler();
	}
	else {
		//如果有block,移除的动作由用户自己操作具有更大的灵活性.
		[self removeFromSuperview];
	}
}

#pragma mark 1 DisplayMessage
- (void)displayMessage:(NSString *)message {
	[self displayMessage:message contentType:JsMessageReminderContentTypeInfo arrangeType:JsMessageReminderArrangeTypeHorizontal colorType:JsMessageReminderColorTypeColor];
}


- (void)displayMessage:(NSString *)message contentType:(JsMessageReminderContentType)contentType {
	[self displayMessage:message contentType:contentType arrangeType:JsMessageReminderArrangeTypeHorizontal colorType:JsMessageReminderColorTypeColor];
}

- (void)displayMessage:(NSString *)message contentType:(JsMessageReminderContentType)contentType arrangeType:(JsMessageReminderArrangeType)arrangeType colorType:(JsMessageReminderColorType)colorType {
	JsMessageReminderViewVm * vm = [JsMessageReminderViewVm vmWithTitle:message contentType:contentType arrangeType:arrangeType colorStyle:colorType];
	//需要设置最大宽度,否则太长了不好看.
	vm.maxWidth = self.superview.frame.size.width - 20;
	JsMessageReminderView * view = [[JsMessageReminderView alloc] initWithVm:vm];
	JsDisplayStyle * style = [JsDisplayStyle defaulStyle];
	style.mf_displayTime = 2;
	style.maskColor = [UIColor clearColor];
	style.mb_isHasShadow = NO;
	style.mb_isMaskCancellable = NO;
	[view displayInView:self withDisplayStyle:style undisplayCompletionHandler:nil];
}

- (void)displayMessage:(NSString *)message duration:(float)duration {
	UIImage * image = [UIImage imageNamed:@"buble.png"];
	JsMessageReminderViewVm * vm = [JsMessageReminderViewVm vmWithTitle:message contentType:JsMessageReminderContentTypeInfo arrangeType:JsMessageReminderArrangeTypeHorizontal colorStyle:JsMessageReminderColorTypeColor];
	vm.maxWidth = self.frame.size.width - 100;
	vm.image = image;
	JsMessageReminderView * view = [[JsMessageReminderView alloc]initWithVm:vm];
	
	JsDisplayStyle * style = [JsDisplayStyle defaulStyle];
	style.mf_displayTime = duration;
	style.maskColor = [UIColor clearColor];
	style.mb_isHasShadow = NO;
	style.mb_isMaskCancellable = NO;
	[view displayInView:self withDisplayStyle:style undisplayCompletionHandler:nil];
}

#pragma mark 1.4 最后的构造方法.
- (void)displayMessage:(NSString *)message image:(UIImage *)image style:(JsDisplayStyle *)style {
	JsMessageReminderViewVm * vm = [JsMessageReminderViewVm vmWithTitle:message contentType:JsMessageReminderContentTypeInfo arrangeType:JsMessageReminderArrangeTypeHorizontal colorStyle:JsMessageReminderColorTypeColor];
	vm.maxWidth = self.frame.size.width - 100;
	vm.image = image;
	JsMessageReminderView * view = [[JsMessageReminderView alloc]initWithVm:vm];
	[view displayInView:self withDisplayStyle:style undisplayCompletionHandler:nil];
}

/**
 需要判断是否已经有toast,如果已经有了,toastCount++;
 */
- (void)displayLoading {
	NSNumber * num_toastCount = objc_getAssociatedObject(self, &kToastCount);
	int i_toastCount = num_toastCount.intValue;
	if(i_toastCount) {
		//已经存在.toastCount++;
		i_toastCount ++;
		objc_setAssociatedObject(self, &kToastCount, @(i_toastCount), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}
	else {
		//没有创建新的toast并显示
		JsActivityReminderView * toast = [JsActivityReminderView defalutView];
			   JsDisplayStyle * style = [JsDisplayStyle defaulStyle];
		style.mb_isMaskCancellable = NO;
		[toast displayInView:self withDisplayStyle:style undisplayCompletionHandler:nil];
		objc_setAssociatedObject(self, &kToastCount, @(1), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
		objc_setAssociatedObject(self, &kMessageReminderView,toast, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}
}



- (void)undisplayLoading {
	NSNumber * num_toastCount = objc_getAssociatedObject(self, &kToastCount);
	int i_toastCount = num_toastCount.intValue;
	
	if(i_toastCount>1) {
		//大于1个,只让toastCount-1;
		i_toastCount--;
		objc_setAssociatedObject(self, &kToastCount, @(i_toastCount), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}
	else {
		//1个,则消失
		UIView * displayView = objc_getAssociatedObject(self, &kMessageReminderView);
		[displayView undisplay];
		objc_setAssociatedObject(self, &kToastCount, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
		objc_setAssociatedObject(self, &kMessageReminderView,nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}
}


#pragma mark 4 Delegate

#pragma mark 5 Event

@end
